package com.maybach.web.framework.interceptor;

import com.maybach.web.constants.WebConstants;
import com.maybach.web.framework.util.CSRFTool;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by houenxun on 15/12/9.
 * 防止表单重复提交
 */
public class CsrfTokenInterceptor extends HandlerInterceptorAdapter {
    public static final String DEFAULT_TOKEN_KEY = CSRFTool.CSRF_PARAM_NAME;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 只拦截post请求  跳转不出去 还在想办法
        if (request.getMethod().toUpperCase().equals(RequestMethod.POST.name()) && null == request.getAttribute(this.getClass().getSimpleName())) {
            String token = StringUtils.trimToNull(request.getParameter(DEFAULT_TOKEN_KEY));
            //
            if (StringUtils.isNotBlank(token)) {
                String innerToken = CSRFTool.getToken(request);
                CSRFTool.clearTokenFromCache(request, null);
                if (!StringUtils.equals(innerToken, token)) {
                    // 防止死循环
                    request.setAttribute("CommonResultCode", "CSRF_TOKEN_EXPIRED");
                    request.setAttribute(this.getClass().getSimpleName(), true);
                    request.getRequestDispatcher(WebConstants.COMMON_RESULT_PAGE + ".htm").forward(request, response);
                }
            }
        }
        return super.preHandle(request, response, handler);
    }


}
